<template>
  <div class="edit-player">
    <el-dialog
      :title="title"
      :visible="visible"
      width="600px"
      append-to-body
      @close="handleClose"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.avatar" :src="form.avatar" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="name">
          <el-input v-model="form.name" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNum">
          <el-input v-model="form.phoneNum" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="form.status"
            placeholder="请选择状态"
            style="width: 100%"
          >
            <el-option label="存活" :value="1" />
            <el-option label="已淘汰" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定臂环" prop="deviceId">
          <el-input v-model="form.deviceId" placeholder="请输入臂环ID" />
        </el-form-item>
        <el-form-item label="微信ID" prop="wechatId">
          <el-input v-model="form.wechatId" placeholder="请输入微信ID" />
        </el-form-item>
        <el-form-item label="粉丝数" prop="fansCount">
          <el-input
            v-model.number="form.fansCount"
            placeholder="请输入粉丝数"
            type="number"
            @input="handleNumberInput($event, 'fansCount')"
          />
        </el-form-item>
        <el-form-item label="淘汰值" prop="expireValue">
          <el-input
            v-model.number="form.expireValue"
            placeholder="请输入淘汰值"
            type="number"
            @input="handleNumberInput($event, 'expireValue')"
          />
        </el-form-item>
        <el-form-item label="自定义值" prop="customizeValue">
          <el-input
            v-model.number="form.customizeValue"
            placeholder="请输入自定义值"
            type="number"
            @input="handleNumberInput($event, 'customizeValue')"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm" :loading="loading"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addPlayer, updatePlayer } from "@/api/player";

export default {
  name: "EditPlayer",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "新选手",
    },
  },
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      loading: false,
      form: {
        id: undefined,
        name: "",
        password: "",
        phoneNum: "",
        gender: 1,
        avatar: "",
        status: 1,
        deviceId: "",
        wechatId: "",
        fansCount: "",
        expireValue: "",
        customizeValue: "",
      },
      rules: {
        name: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        phoneNum: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: "请输入正确的手机号",
            trigger: "blur",
          },
        ],
        gender: [{ required: true, message: "请选择性别", trigger: "change" }],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
        deviceId: [
          { required: true, message: "请输入臂环ID", trigger: "blur" },
        ],
        wechatId: [
          { required: true, message: "请输入微信ID", trigger: "blur" },
        ],
        fansCount: [
          { required: true, message: "请输入粉丝数", trigger: "blur" },
          { type: "number", message: "请输入数字", trigger: "change" },
        ],
        expireValue: [
          { required: true, message: "请输入淘汰值", trigger: "blur" },
          { type: "number", message: "请输入数字", trigger: "change" },
        ],
        customizeValue: [
          { required: true, message: "请输入自定义值", trigger: "blur" },
          { type: "number", message: "请输入数字", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.form.avatar = res.url;
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.indexOf("image/") === 0;
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error("上传头像图片只能是图片格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isImage && isLt2M;
    },
    setFormData(data) {
      this.$nextTick(() => {
        this.form = {
          id: data.id,
          name: data.name,
          password: data.password,
          phoneNum: data.phoneNum,
          gender: parseInt(data.gender),
          avatar: data.avatar,
          status: parseInt(data.status),
          deviceId: data.deviceId,
          wechatId: data.wechatId,
          fansCount: parseInt(data.fansCount || 0),
          expireValue: parseInt(data.expireValue || 0),
          customizeValue: parseInt(data.customizeValue || 0),
        };
        if (this.$refs.form) {
          this.$refs.form.clearValidate();
        }
      });
    },
    cancel() {
      this.resetForm();
      this.handleClose();
    },
    resetForm() {
      this.form = {
        id: undefined,
        name: "",
        password: "",
        phoneNum: "",
        gender: 1,
        avatar: "",
        status: 1,
        deviceId: "",
        wechatId: "",
        fansCount: "",
        expireValue: "",
        customizeValue: "",
      };
      if (this.$refs.form) {
        this.$refs.form.resetFields();
      }
    },
    handleNumberInput(value, field) {
      if (value === "" || value === null || value === undefined) {
        this.form[field] = 0;
        return;
      }
      const numValue = parseInt(value.toString().replace(/[^\d]/g, ""));
      this.form[field] = isNaN(numValue) ? 0 : numValue;
    },
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          const isEdit = this.form.id !== undefined;
          const apiMethod = isEdit ? updatePlayer : addPlayer;

          const submitData = {
            ...this.form,
            fansCount: parseInt(this.form.fansCount || 0),
            expireValue: parseInt(this.form.expireValue || 0),
            customizeValue: parseInt(this.form.customizeValue || 0),
            status: parseInt(this.form.status),
          };

          apiMethod(submitData)
            .then(() => {
              this.$modal.msgSuccess(isEdit ? "修改成功" : "新增成功");
              this.$emit("success");
              this.cancel();
            })
            .catch((error) => {
              console.error(isEdit ? "修改失败" : "新增失败:", error);
              this.$modal.msgError(
                error.message || (isEdit ? "修改失败" : "新增失败")
              );
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },
    handleClose() {
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style scoped>
.edit-player {
  .el-dialog {
    margin-top: 8vh !important;
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
